﻿using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DataBaseBackUpUtil
{
    public class TaskManage
    {
        private static IScheduler scheduler;
        private static IScheduler GetScheduler()
        {
            if (null == scheduler)
            {
                scheduler = StdSchedulerFactory.GetDefaultScheduler();
            }

            return scheduler;
        }

        public static void StartTask(Dictionary<string,string> JobData)
        {
            IScheduler scheduler = GetScheduler();
            IJobDetail job = JobBuilder.Create(Type.GetType("DataBaseBackUpUtil.BackUpJob")).Build();
            TriggerBuilder builder = TriggerBuilder.Create().WithIdentity("定时任务计划", "System");
            string Minute = string.Empty;
            string Hour = string.Empty;
            JobData.TryGetValue("Minute", out Minute);
            JobData.TryGetValue("Hour", out Hour);
            string cornexpress = string.Format("0 {0} {1} ? * * ", Minute, Hour);
            //声明具体的执行时间
            builder.WithCronSchedule(cornexpress);
            ITrigger trigger = builder.Build();
            //传递数据
            foreach (var item in JobData)
            {
                job.JobDataMap.Put(item.Key, item.Value);
            }
            scheduler.ScheduleJob(job, trigger);
            scheduler.Start();
        }

        public static void RemoveTask()
        {
            IScheduler scheduler = GetScheduler();
            TriggerKey triggerkey = new TriggerKey("定时任务计划", "System");
            //停止job
            scheduler.ResumeJob(scheduler.GetTrigger(triggerkey).JobKey);
            //删除相关的job任务 
            scheduler.DeleteJob(scheduler.GetTrigger(triggerkey).JobKey);

        }

        public static void StopTask()
        {
            IScheduler scheduler = GetScheduler();
            if (scheduler.IsStarted)
            {
                scheduler.PauseAll();
                scheduler.Clear();
                scheduler.Shutdown(true);
            }
       
        }

 
    }
}
